<template>
  <el-dialog
    :model-value="props.modelValue"
    @update:model-value="emit('update:modelValue', $event)"
    :title="isEdit ? '编辑关键词' : '新增关键词'"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="keywordFormRef"
      :model="keywordForm"
      :rules="formRules"
      label-width="100px"
      class="keyword-form"
    >
      <!-- 所属部门 -->
      <el-form-item label="所属部门" prop="department">
        <el-select
          v-model="keywordForm.department"
          placeholder="请选择关键词所属的部门"
          style="width: 100%"
          :disabled="isEdit"
        >
          <el-option
            v-for="dept in departmentOptions"
            :key="dept.value"
            :label="dept.label"
            :value="dept.value"
          />
        </el-select>
        <div class="form-hint">💡 提示: 选择关键词所属的部门</div>
      </el-form-item>

      <!-- 关键词内容 -->
      <el-form-item label="关键词内容" prop="keyword">
        <el-input
          v-model="keywordForm.keyword"
          placeholder="请输入关键词"
          maxlength="50"
          :disabled="isEdit"
          @blur="handleKeywordBlur"
        />
        <div class="form-hint">
          💡 提示:<br />
          - 支持中文、英文、数字<br />
          - 建议2-10个字符<br />
          - 避免过于宽泛的词(如"管理"、"系统")
        </div>
      </el-form-item>

      <!-- 关键词权重 -->
      <el-form-item label="关键词权重" prop="weight">
        <el-input-number
          v-model="keywordForm.weight"
          :min="0.1"
          :max="1.0"
          :step="0.1"
          :precision="1"
          style="width: 100%"
        />
        <div class="form-hint">
          💡 权重说明:<br />
          - 0.9-1.0: 极强相关 (专有名词)<br />
          - 0.7-0.8: 强相关 (常用术语)<br />
          - 0.5-0.6: 中等相关 (通用词汇)<br />
          - 0.1-0.4: 弱相关 (备选词)
        </div>
      </el-form-item>

      <!-- 备注说明 -->
      <el-form-item label="备注说明">
        <el-input
          v-model="keywordForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注说明（可选）"
          maxlength="200"
        />
      </el-form-item>

      <!-- 智能检测结果 -->
      <el-form-item v-if="suggestionData" label="智能检测结果">
        <div class="suggestion-box">
          <div class="suggestion-title">
            ✅ 智能检测结果:
          </div>
          <div class="suggestion-content">
            <div class="suggestion-item">
              🔍 当前数据库中包含"{{ keywordForm.keyword }}"的资产:
            </div>
            <div class="suggestion-item">
              - 总数: {{ suggestionData.existing_assets || 0 }}个
            </div>
            <div v-if="suggestionData.department_distribution" class="suggestion-item">
              - 分布:
              <span
                v-for="(count, dept) in suggestionData.department_distribution"
                :key="dept"
                class="distribution-item"
              >
                {{ dept }}({{ count }})
              </span>
            </div>
            <div v-if="suggestionData.suggested_weight" class="suggestion-tip">
              💡 建议: 该关键词在{{ keywordForm.department }}出现率较高,
              建议权重设为 {{ suggestionData.suggested_weight }}
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import type { ElForm } from "element-plus";
import { getKeywordSuggestion } from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  keyword: {
    type: Object,
    default: () => ({}),
  },
  isEdit: { type: Boolean, default: false },
  departmentOptions: {
    type: Array as () => Array<{ label: string; value: string }>,
    default: () => [],
  },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "save", keyword: any): void;
}>();

// 表单引用
const keywordFormRef = ref<InstanceType<typeof ElForm>>();
const saving = ref(false);

// 表单数据
const keywordForm = reactive({
  id: null as number | null,
  department: "",
  keyword: "",
  weight: 0.8,
  remark: "",
});

// 智能检测结果
const suggestionData = ref<{
  existing_assets?: number;
  department_distribution?: Record<string, number>;
  suggested_weight?: number;
} | null>(null);

// 表单规则
const formRules = reactive({
  department: [{ required: true, message: "请选择所属部门", trigger: "change" }],
  keyword: [
    { required: true, message: "请输入关键词内容", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "关键词长度应在2-50个字符之间",
      trigger: "blur",
    },
  ],
  weight: [
    { required: true, message: "请输入关键词权重", trigger: "blur" },
    {
      type: "number",
      min: 0.1,
      max: 1.0,
      message: "权重应在0.1-1.0之间",
      trigger: "blur",
    },
  ],
});

// 监听visible变化
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      if (props.isEdit && props.keyword) {
        // 编辑模式：填充表单
        const keyword = props.keyword;
        keywordForm.id = keyword.id;
        keywordForm.department = keyword.department || "";
        keywordForm.keyword = keyword.keyword || "";
        keywordForm.weight = keyword.weight || 0.8;
        keywordForm.remark = keyword.remark || "";
        // 编辑模式下不显示智能检测
        suggestionData.value = null;
      } else {
        // 新增模式：重置表单
        keywordForm.id = null;
        keywordForm.department = "";
        keywordForm.keyword = "";
        keywordForm.weight = 0.8;
        keywordForm.remark = "";
        suggestionData.value = null;
      }
    } else {
      // 关闭弹窗时重置表单
      keywordFormRef.value?.resetFields();
      suggestionData.value = null;
    }
  },
  { immediate: true }
);

// 关键词失焦时获取智能检测结果
const handleKeywordBlur = async () => {
  if (!props.isEdit && keywordForm.keyword && keywordForm.keyword.length >= 2) {
    try {
      const { data } = await getKeywordSuggestion(keywordForm.keyword);
      if (data) {
        suggestionData.value = data;
        // 如果有建议权重，自动填充
        if (data.suggested_weight && !keywordForm.weight) {
          keywordForm.weight = data.suggested_weight;
        }
      }
    } catch (error: any) {
      // 获取建议失败不影响主流程，静默失败
      console.error("获取关键词建议失败:", error);
    }
  }
};

// 保存
const handleSave = async () => {
  const valid = await keywordFormRef.value?.validate();
  if (!valid) return;

  saving.value = true;
  try {
    emit("save", { ...keywordForm });
  } finally {
    saving.value = false;
  }
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.keyword-form {
  padding: 10px 0;

  .form-hint {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    line-height: 1.6;
  }

  .suggestion-box {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 12px;
    background-color: #f5f7fa;

    .suggestion-title {
      font-weight: 500;
      color: #303133;
      margin-bottom: 8px;
    }

    .suggestion-content {
      color: #606266;
      font-size: 13px;
      line-height: 1.8;

      .suggestion-item {
        margin-bottom: 4px;
      }

      .distribution-item {
        margin-left: 4px;
        margin-right: 8px;
      }

      .suggestion-tip {
        margin-top: 8px;
        padding-top: 8px;
        border-top: 1px solid #e4e7ed;
        color: #409eff;
        font-weight: 500;
      }
    }
  }
}
</style>
